package com.xadmin.sys.rbac.controller;

import com.xadmin.sys.common.AllCtrl;
import com.xadmin.sys.common.response.Result;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

@RestController
@Api(value = "万能接口",tags = "万能接口")
public class AllController {

    public static Connection getConnection() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setMaxWait(-1);
        dataSource.setMinIdle(1);
        dataSource.setInitialSize(1);
        dataSource.setMaxActive(2);
        dataSource.setKeepAlive(true);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestOnReturn(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setBreakAfterAcquireFailure(true);
        dataSource.setTimeBetweenEvictionRunsMillis(60000);
        dataSource.setPhyTimeoutMillis(3600 * 24 * 1000);
        dataSource.setTimeBetweenConnectErrorMillis(600000);
        dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setPassword("lqylqy");
        dataSource.setValidationQuery("select 1");
        String ip = "localhost";
        String port = "3306";
        String db = "xadmin";
        String url = "jdbc:mysql://" + ip + ":" + port + "/" + db + "?useSSL=false&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true&allowLoadLocalInfile=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8";
        dataSource.setUrl(url);
        return dataSource.getConnection();
    }

    @RequestMapping(value = "/all",method = RequestMethod.POST)
    @ApiOperation(value = "万能接口",notes = "万能接口")
    public static Result executeDML(@RequestBody AllCtrl allCtrl) throws SQLException {
        Connection conn = null;
        Statement statement = null;
        try{
            String sql = allCtrl.getSql();
            boolean isQuery = allCtrl.getDoQuery()==1?true:false;
            boolean isList = allCtrl.getDoList()==1?true:false;
            boolean isCount = allCtrl.getDoCount()==1?true:false;
            conn = getConnection();
            statement =conn.createStatement();
            if(isQuery){
                ResultSet rs = statement.executeQuery(sql);
                int columnCount = rs.getMetaData().getColumnCount();
                if(isList){
                    List<JSONObject> list = new ArrayList<>();
                    while (rs.next()){
                        JSONObject object = new JSONObject();
                        for (int i = 1; i <= columnCount; i++) {
                            if(rs.getMetaData().getColumnType(i)==4){
                                object.put(rs.getMetaData().getColumnName(i),rs.getInt(i));
                            }else {
                                object.put(rs.getMetaData().getColumnName(i),rs.getString(i));
                            }
                        }
                        list.add(object);
                    }
                    return Result.ok().data("data",list);
                }else if(isCount){
                    rs.next();
                    int count = rs.getInt(1);
                    return Result.ok().data("data",count);
                }else{
                    JSONObject object = new JSONObject();
                    while (rs.next()){
                        for (int i = 1; i <= columnCount; i++) {
                            if(rs.getMetaData().getColumnType(i)==4){
                                object.put(rs.getMetaData().getColumnName(i),rs.getInt(i));
                            }else {
                                object.put(rs.getMetaData().getColumnName(i),rs.getString(i));
                            }
                        }
                    }
                    return Result.ok().data("data",object);
                }
            }else {
                if(statement.execute(sql)){
                    return Result.ok().message("操作成功！");
                }else {
                    return Result.error().message("操作失败！");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            return Result.error().message("操作失败！");
        }finally {
            statement.close();
            conn.close();
        }
    }

}
